<template>
  <div class="app-container">
    
<br>
<br>
    <el-button type="primary" @click="add">添加模板</el-button>
    <br>
    <br>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    > 
      <el-table-column align="center" label="序号" width="50">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="模板名称" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="所属科室" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.jobOfficeName }}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="操作" align="center" width="300" >
        <template slot-scope="scope">
          <el-button type="primary"  @click="getInfo(scope.row)" size="small">详情</el-button>
          <el-button type="success"  @click="update(scope.row)" size="small">修改</el-button>
          <el-button type="danger" @click="deleteInfo(scope)" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="->, total, prev, pager, next"
      :total="this.total"
      :current-page="currentPage"
      :page-size="pageSize"
      @current-change="clickCurPage"
      >
    </el-pagination>
  <el-dialog title="模板详情" :visible.sync="infoVisible" width="1200px">
      <h2>模板信息</h2>
      <el-form ref="info" :model="info" label-width="120px">
        <el-form-item label="所属科室">
          <el-select v-model="info.jobOffice" placeholder="请选择" :disabled="true" >
            <el-option
              v-for="item in jobOfficeEnum"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模板名称">
            <el-input v-model="info.name" :disabled="true" />
        </el-form-item>
        <div style="width:100%;border: 2px solid #E4E7ED;padding: 10px;">
          <div v-for="(template, index) in info.templateDetailList" :key="index">
            <el-row :gutter="10">
              <el-col :span=4 >
                <el-form-item label="名称" label-width="40px">
                  <el-input v-model="template.column"  :disabled="true"/>
                </el-form-item>
              </el-col>
              <el-col :span=4 >
                <el-form-item label="是否必填" label-width="80px">
                  <el-select v-model="template.required" placeholder="请选择" :disabled="true">
                    <el-option
                      v-for="item in requiredEnum"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span=4 >
                <el-form-item label="类型" label-width="40px">
                  <el-select v-model="template.type" placeholder="请选择" :disabled="true">
                    <el-option
                      v-for="item in typeEnum"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span=11 >
                <el-form-item label="选项值" v-if="template.type === 2" label-width="60px">
                  <div style="width:100%;border: 1px solid #E4E7ED;padding: 10px;">
                    <el-tag
                      :key="tag"
                      v-for="tag in template.typeValues"
                      >
                      {{tag}}
                    </el-tag>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
        
      </el-form>
  </el-dialog>
  <el-dialog :title="dialogTitle" :visible.sync="formVisible" :closeOnClickModal="false" width="1200px">
      <h2>模板信息</h2>
      <el-form ref="form" :model="form" label-width="120px" :rules="formRules">
        <el-form-item label="所属科室">
          <el-select v-model="form.jobOffice" placeholder="请选择">
            <el-option
              v-for="item in jobOfficeEnum"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模板名称">
            <el-input v-model="form.name" />
        </el-form-item>
        <div style="width:100%;border: 2px solid #E4E7ED;padding: 10px;">
          <div v-for="(template, index) in form.templateDetailList" :key="index">
            <el-row :gutter="10">
              <el-col :span=1 >
                <el-button type="danger" icon="el-icon-delete" circle @click="deleteTemplate(template, form.templateDetailList)"></el-button>
              </el-col>
              <el-col :span=4 >
                <el-form-item label="名称" label-width="40px">
                  <el-input v-model="template.column" />
                </el-form-item>
              </el-col>
              <el-col :span=4 >
                <el-form-item label="是否必填" label-width="80px">
                  <el-select v-model="template.required" placeholder="请选择">
                    <el-option
                      v-for="item in requiredEnum"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span=4 >
                <el-form-item label="类型" label-width="40px">
                  <el-select v-model="template.type" placeholder="请选择">
                    <el-option
                      v-for="item in typeEnum"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span=11 >
                <el-form-item label="选项值" v-if="template.type === 2" label-width="60px">
                  <div style="width:100%;border: 1px solid #E4E7ED;padding: 10px;">
                    <el-tag
                      :key="tag"
                      v-for="tag in template.typeValues"
                      closable
                      :disable-transitions="false"
                      @close="handleClose(tag, template.typeValues)">
                      {{tag}}
                    </el-tag>
                    <el-input
                      class="input-new-tag"
                      v-if="template.inputVisible"
                      v-model="inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(template)"
                      @blur="handleInputConfirm(template)"
                    >
                    </el-input>
                    <el-button v-else class="button-new-tag" size="small" @click="showInput(template)">添加选项值</el-button>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <el-button type="primary" @click="addTemplate">添加选项</el-button>
        </div>
        
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirm">确 定</el-button>
          <div style="width:200px;display: inline-block;"> </div>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
      
  </el-dialog>
  </div>
</template>

<script>

import { getList, getListByJobOfficeId, addOrUpdate} from '@/api/guidanceTemplate'
import { getList as getJobOfficeList} from '@/api/jobOffice'


export default {
  name: "Template",
  filters: {

  },
  data() {
    const validateName = (rule, value, callback) => {
      if (!value) callback(new Error('请输入名称')) 
      else callback()
    }
    const validatejobOffice = (rule, value, callback) => {
      if (!value) callback(new Error('请选择科室')) 
      else callback()
    }
    return {
      list: null,
      listLoading: true,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      curIndex: -1,
      infoVisible: false,
      formVisible: false,
      info: {},
      form: {},
      dialogTitle: '添加模板',
      jobOfficeEnum:[],
      requiredEnum: [{id: 1, name: '是'}, {id: 2, name: '否'}],
      typeEnum: [{id: 1, name: '输入框'}, {id: 2, name: '选择框'}],
      formRules: {
        name: [{ required: true, trigger: 'blur', validator: validateName }],
        jobOffice: [{ required: true, trigger: 'blur', validator: validatejobOffice }],
      },
      inputValue: '',
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      getList({currentPage: this.currentPage, pageSize: this.pageSize}).then(res=>{
        console.log(res)
        this.list = res.data
        this.list.forEach(item=> {
          item.templateDetailList.forEach(templateDetail=> {
            templateDetail.required = templateDetail.required?1:2
          })
        })
        this.listLoading = false
      }).catch(err=>{
        console.log("err")
        console.log(err)
        this.listLoading = false
      })
      getJobOfficeList().then(jobOfficeRes=>{
        console.log(jobOfficeRes)
        this.jobOfficeEnum = jobOfficeRes.data
      })
    },
    clickCurPage(val){
      this.currentPage = val
      this.fetchData()
    },
    getInfo(row) {
      this.info = row
      this.infoVisible = true
    },
    update(row) {
      this.reset()
      this.dialogTitle = '修改模板'
      this.form = JSON.parse(JSON.stringify(row))
      this.formVisible = true
    },
    deleteInfo(scope) {
      console.log(scope.row)
      this.$confirm('确定删除该模板?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(scope.row.id).then(res=>{
          this.list.splice(scope.$index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(err=>{
          console.log(err)
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    add(row) {
      this.reset()
      this.dialogTitle = '添加模板'
      this.$set(this.form, 'templateDetailList', [])
      this.formVisible = true
    },
    confirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          console.log(this.form)
          this.form.templateDetailList.forEach(templateDetail=> {
            templateDetail.required = templateDetail.required === 1 ? true : false
          })
          addOrUpdate(this.form).then(res=>{
            console.log(res)
            this.$message({
              message: '修改成功',
              type: 'success'
            })
              this.formVisible = false
              this.listLoading = false
              this.$tab.refreshPage({path: '/guidance/template', name: "Template"})
          }).catch(err=>{
            console.log(err)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    cancel() {
      this.formVisible = false
    },
    reset(){
      this.form = {}
    },
    handleClose(tag, typeValues) {
      typeValues.splice(typeValues.indexOf(tag), 1);
    },
    showInput(template) {
      this.$set(template, 'inputVisible', true)
      // template.inputVisible = true;
    },
    handleInputConfirm(template) {
      console.log(template)
      let inputValue = JSON.parse(JSON.stringify(this.inputValue));
      if (inputValue) {
        template.typeValues.push(inputValue);
      }
      template.inputVisible = false;
      this.inputValue = '';
    },
    addTemplate() {
      this.form.templateDetailList.push({inputVisible: false, typeValues: []})
    },
    deleteTemplate(template, list) {
      list.splice(list.indexOf(template), 1);
    }
  }
}
</script>

<style>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>